/**
 * 管理后台路由(Vue做的管理后台，与服务端分离)
 * @param app
 */
module.exports = app => {
    const express = require('express'); //引入express
    const router = express.Router();//创建路由模块
    const usertoken = require('../../usertoken');//token验证模块

    /**
     *
     * ====核心路由====
     *
     * 利用动态路由区分接口要连接哪个数据表，动态路由名称==表名
     * 统一做处理，处理完继续往下分发
     */
    app.use('/admin/:resource', async (req, res, next) => {
        const modelName = require('inflection').classify(req.params.resource);
        try {
            req.Model = require(`../../models/${modelName}`);
            next()
        } catch (e) {
            next()
        }
    }, router);


    /**
     * 登录接口
     */
    router.post('/login', async (req, res) => {
        const username = req.body.username;
        const user = await req.Model.findOne({username: username});
        if (user == null) {
            //用户不存在
            res.send({
                    code: 401,
                    msg: "用户不存在"
                }
            )
        } else {
            //非首次登录，验证密码，然后发放token
            if (user.password === req.body.password) {
                //生成Token
                const token = usertoken.creatToken(user._id, user.username);
                res.send({
                        code: 200,
                        msg: "success",
                        token: token
                    }
                )
            }else {
                res.send({
                        code: 401,
                        msg: "密码错误"
                    }
                )
            }
        }
    });


    /**
     * ====增====
     *
     * 往数据表中插入一条新数据
     */
    router.post('/create', async (req, res) => {
        const data = await usertoken.verToken(req, res);
        if (!data) {
            return
        }
        const model = await req.Model.create(req.body);
        res.send(model)
    });

    /**
     * ====查====
     *
     * 查询某数据表，整个列表
     */
    router.get('/list', async (req, res) => {
        const data = await usertoken.verToken(req, res);
        if (!data) {
            return
        }
        const list = await req.Model.find().limit(100);
        res.send({
            code: 200,
            msg: "success",
            list
        })
    });

    /**
     * ====查====
     *
     * 查询数据表某条详情
     */
    router.get('/item/:id', async (req, res) => {
        const data = await usertoken.verToken(req, res);
        if (!data) {
            return
        }
        const item = await req.Model.findById(req.params.id);
        res.send(item)
    });



    /**
     * ====改====
     *
     * 修改数据表的某一条，对象更新覆盖
     */
    router.post('/item/:id', async (req, res) => {
        const data = await usertoken.verToken(req, res);
        if (!data) {
            return
        }
        const item = await req.Model.findByIdAndUpdate(req.params.id, req.body);
        res.send(item)
    });


    /**
     * ====删====
     *
     * 删除数据表的某条数据
     */
    router.post('/list/:id', async (req, res) => {
        const data = await usertoken.verToken(req, res);
        if (!data) {
            return
        }
        const item = await req.Model.findByIdAndDelete(req.params.id, req.body);
        res.send({
            success: true,
            msg: "删除成功"
        })
    });


    /**
     *  查询所有的评论，
     *
     *  联查：评论表，用户表，电影表
     */
    router.get('/commentsall',async (req,res)=>{
        const data = await usertoken.verToken(req, res);
        if (!data) {
            return
        }
        const list = await req.Model.find().limit(100);
        for (let item of list) {
            const userModel = require('../../models/User');
            const userInfo = await userModel.findOne({_id: item.customid})
            item._doc.nickname = userInfo.nickname;
            item._doc.headicon = userInfo.headicon;

            const movieModel = require('../../models/Movie');
            const movieInfo = await movieModel.findOne({movieId: item.movieId})
            item._doc.movieName = movieInfo.movieName;
            item._doc.cover = movieInfo.cover;
        }

        res.send({
            code:200,
            msg:"success",
            list
        });
    });

};